package com.example.skymallseckillproductapi.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.skymallseckillproductapi.config.AliyunOssConfig;
import com.situ.shop.service.UploadService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;



@Service
public class UploadServiceImpl implements UploadService {
    @Autowired
    private AliyunOssConfig aliyunOssConfig;  // 依赖注入

    private OSS ossClient;  // 先声明，后初始化

    // 构造函数中不做初始化操作
    public UploadServiceImpl() {
    }

    // 依赖注入完成后执行初始化（@PostConstruct注解的方法在构造函数之后执行）
    @PostConstruct
    public void initOssClient() {
        this.ossClient = new OSSClientBuilder().build(
                aliyunOssConfig.getEndpoint(),
                aliyunOssConfig.getAccessKeyId(),
                aliyunOssConfig.getAccessKeySecret()
        );
    }

    // 在uploadImage方法中，修改文件路径生成逻辑
    @Override
    public String uploadImage(MultipartFile file, String type) {
        try {
            // 1. 获取原始文件名
            String originalFilename = file.getOriginalFilename();

            // 2. 生成唯一文件名（解决重名问题）
            String fileName = generateUniqueFileName(originalFilename);

            // 3. 构建文件存储路径（关键修改：去掉开头的斜杠）
            // 错误写法: String objectName = "/" + type + "/" + fileName;
            String objectName = type + "/" + fileName;  // 正确写法，不带开头斜杠

            // 4. 上传文件到OSS
            ossClient.putObject(aliyunOssConfig.getBucketName(), objectName, file.getInputStream());

            // 5. 拼接文件访问URL并返回
            return aliyunOssConfig.getDomain() + "/" + objectName;        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    // 生成唯一文件名的辅助方法
    private String generateUniqueFileName(String originalFilename) {
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成时间戳 + 随机数的唯一文件名
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf(new Random().nextInt(1000));
        return time + "-" + random + suffix;
    }
}